import {showUploadBox} from "../ui";
import {assign} from "../core";

const PLUS_BUTTON_TPL = `
<div class="uploader-item uploader-plus">
	<i class="msicon msicon-img"></i>
</div>
`;

// 获取路径
function getPaths(target) {
	let paths = target.data('path');
	paths = paths ? (typeof paths === 'object' ? paths : paths.trim().split(',')) : [];
	return paths;
}

export default function(options) {
	options = Object.assign({
		max: 9,
		multi: false
	}, options);

	const self = $(options.el);
	const paths = getPaths(self);

	self.addClass('uploader-list');
	self.attr('data-preview', '');

	//图片选择按钮
	const plusItemBtn = $(PLUS_BUTTON_TPL).on('click', function() {
		const length = self.children().length - 1;
		showUploadBox(Object.assign({
			max: options.multi ? options.max - length : 1,
		}, options)).then(function(res) {
			res.forEach(function(item) {
				plusItemHandler(item);
			});
			updatePlusItemBtnStatus();
		});
		return false;
	}).appendTo(self);

	//更新是否显示图片选择按钮
	const updatePlusItemBtnStatus = function() {
		if (options.multi) {
			if (self.children().length >= options.max + 1) {
				plusItemBtn.hide();
			} else {
				plusItemBtn.show();
			}
		} else {
			if (self.children().length > 1) {
				plusItemBtn.hide();
			} else {
				plusItemBtn.show();
			}
		}
	};

	//添加项处理器
	const plusItemHandler = function(path) {
		const TPL = `
<div class="uploader-item">
	<img src="${path}" mode="aspectFill"  alt=""/>
	<input type="hidden" name="${options.name}" value="${path}"/>
	<span class="uploader-btn-remove msicon msicon-close"></span>
</div>
`;
		const item = $(TPL);
		item.find('.uploader-btn-remove').on('click', function() {
			item.remove();
			updatePlusItemBtnStatus();
			return false;
		});
		plusItemBtn.before(item);
	};

	//显示已默认的图片
	paths.forEach(plusItemHandler);
	updatePlusItemBtnStatus();

	//支持拖动排序
	if (window.Sortable) {
		new Sortable(self[0], assign({
			animation: 150,
			filter: ".uploader-plus"
		}, options.sortable || {}));
	}
}
